package com.manage.base.mongo;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Properties;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

/**
 * 
 * mongo客户端
 * <p>
 * 
 * @author dizh
 * 
 */
public class MongoManager {

	static MongoDatabase database = null;
	static MongoClient mongoClient;

	public static void init() throws IOException {
		Properties props = new Properties();
		InputStream in = MongoManager.class.getResourceAsStream("/resources/mongo.properties");
		props.load(in);
		in.close();
		String host = props.getProperty("mongo.host", "127.0.0.1");
		int port = Integer.parseInt(props.getProperty("mongo.port", "27017"));
		String db = props.getProperty("mongo.db", "es_eup");
		boolean auth = Boolean.parseBoolean(props.getProperty("mongo.auth", "false"));
		if (auth) {
			String user = props.getProperty("mongo.user", "");
			String pass = props.getProperty("mongo.password", "");
			MongoCredential mc = MongoCredential.createCredential(user, db, pass.toCharArray());
			ServerAddress sa = new ServerAddress(host, port);
			mongoClient = new MongoClient(sa, Arrays.asList(mc));
		} else {
			mongoClient = new MongoClient(host, port);
		}
		// mongoClient.setWriteConcern(WriteConcern.JOURNALED);
		database = mongoClient.getDatabase(db);
	}

	public static void destroy() {
		if (mongoClient != null) {
			mongoClient.close();
		}
	}

	public static MongoCollection<Document> getCollection(String collectionName) {
		MongoCollection<Document> collection = database.getCollection(collectionName);
		// collection.withWriteConcern(WriteConcern.JOURNALED);
		return collection;
	}

}
